import axios from 'axios'
import { Message } from 'view-design';
import {setStore} from "@/libs/storage";
import {constantRouterMap} from '../router/routers'
import errorCode from "@/libs/errorCode";
import {getToken} from "@/libs/util";
import Cookies from 'js-cookie'
const request = axios.create({
  // API 请求的默认前缀
  baseURL: '/api',
  timeout: 6000,
  headers: { "Content-Type": "application/json;charset=utf-8" }, //即将被发送的自定义请求头
  withCredentials: true, //表示跨域请求时是否需要使用凭证
})
request.interceptors.request.use(function (config) {
  const token = getToken()
  if (token) {
    config.headers['Authorization'] = 'Bearer '+token
  }
  return config
},err => {
  Message.error('请求超时');
  return Promise.resolve(err);
});
const errorHandler = (error) => {
  if (error.response) {
    const data = error.response.data
    const status = error.response.status
    const message = errorCode[status] || data.msg || errorCode['default']
    if (status === 401) {
      Message.error(data.msg)
    } else {
      Message.error(message);
    }
  }
  return Promise.reject(error)
}
// http response 拦截器
request.interceptors.response.use(response => {
  const data = response.data;
  switch (data.code) {
    case 401:
      // 未登录 清除已登录状态
      Cookies.set('userInfo', '');
      setStore('accessToken', '');
      if (constantRouterMap.history.current.name != "login") {
        if (data.message !== null) {
          Message.error(data.message);
        } else {
          Message.error("未知错误，请重新登录");
        }
        constantRouterMap.push('/login');
      }
      break;
    case 403:
      // 没有权限
      if (data.msg !== null) {
        Message.error(data.msg);
      } else {
        Message.error("未知错误");
      }
      break;
    case 500:
      // 错误
      if (data.msg !== null) {
        Message.error(data.msg);
      } else {
        Message.error("未知错误");
      }
      break;
    default:
      return data;
  }
  return data;
}, errorHandler);
export default request;
